package org.jeecg.modules.middleware.quartz.job;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.modules.third.amap.dto.MapDirectionDTO;
import org.jeecg.modules.third.amap.service.AmapService;
import org.jeecg.modules.wlhy.order.entity.HyOrder;
import org.jeecg.modules.wlhy.order.service.IHyOrderService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Service
@Slf4j
public class InsertMileageJobService implements Job{

    @Autowired
    private IHyOrderService hyOrderService;

    @Autowired
    private AmapService amapService;


    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        QueryWrapper<HyOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_status","2");//发布状态
        queryWrapper.eq("order_type","2"); //货源类型(1指派2发布到货源大厅)
        Page<HyOrder> page = new Page<HyOrder>(1, 100);
        IPage<HyOrder> pageList = hyOrderService.page(page, queryWrapper);
        for (HyOrder order:pageList.getRecords()){
            if (order.getMileage()==null||order.getMileage().compareTo(BigDecimal.ZERO)==0){
                //众汇要求货源部分添加里程数
                try {
                    MapDirectionDTO mapDirectionDTO = this.amapService.getEstimateMileageForOrder(order);
                    if (ObjectUtil.isEmpty(mapDirectionDTO)) {
                        throw new JeecgBootException("高德轨迹数据不正确，请确认收发货地址");
                    }
                    order.setMileage(new BigDecimal(mapDirectionDTO.getDistance()));
                    log.info("开始修改货源里程数");
                    hyOrderService.updateById(order);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }

    }
}
